<template>
  <div class="company-setting-container">
    <!-- 操作按钮区域 -->
    <action-buttons
      :buttons="buttonsConfig"
      :selected-data="selectedRows"
      :no-confirm-buttons="['log', 'export']"
      @add="handleAdd"
      @delete="handleDelete"
      @export="handleExport"
      @log="handleLog"
    />
    
    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="company-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 操作列 -->
      <template #operation="{ row }">
        <theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
      </template>
    </custom-table>
    
    <!-- 公司信息弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px" 
      destroy-on-close 
      class="base-dialog"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="companyFormRef" 
        :model="companyForm" 
        :rules="companyFormRules" 
        label-width="100px"
        class="base-form"
      >
        <div class="form-row">
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="companyForm.name" placeholder="请输入公司名称"></el-input>
          </el-form-item>
          <el-form-item label="公司简称" prop="shortName">
            <el-input v-model="companyForm.shortName" placeholder="请输入公司简称"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="公司编码" prop="code">
            <el-input v-model="companyForm.code" placeholder="请输入公司编码"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="companyForm.contactPerson" placeholder="请输入联系人"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="companyForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row full-width">
          <el-form-item label="备注" prop="remark" class="full-width-item">
            <el-input 
              v-model="companyForm.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 日志弹窗 -->
    <log-dialog
      v-model:visible="logDialogVisible"
      :log-data="logData"
      :total="logPagination.total"
      :current-page="logPagination.currentPage"
      :page-size="logPagination.pageSize"
      @size-change="handleLogSizeChange"
      @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格列配置
const tableColumns = [
  { prop: 'name', label: '公司名称', minWidth: 150 },
  { prop: 'shortName', label: '公司简称', minWidth: 120 },
  { prop: 'code', label: '公司编码', minWidth: 120 },
  { prop: 'contactPerson', label: '联系人', minWidth: 100 },
  { prop: 'contactPhone', label: '联系电话', minWidth: 120 },
  { prop: 'createTime', label: '操作时间', minWidth: 160 },
  { prop: 'operator', label: '操作人', minWidth: 100 },
  { prop: 'operation', label: '操作', minWidth: 100, fixed: 'right' }
]

// 操作按钮配置
const buttonsConfig = ref({
  add: { visible: true, order: 1, type: 'primary' },
  delete: { visible: true, order: 2 },
})

// 表格操作权限
const tablePermissions = ref({
  edit: true
})

// 表格数据相关
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增公司')
const companyFormRef = ref(null)
const companyForm = reactive({
  id: '',
  name: '',
  shortName: '',
  code: '',
  contactPerson: '',
  contactPhone: '',
  remark: ''
})

// 表单校验规则
const companyFormRules = {
  name: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  shortName: [
    { required: true, message: '请输入公司简称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入公司编码', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 日志弹窗相关
const logDialogVisible = ref(false)
const logData = ref([])
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    // 模拟异步请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    tableData.value = [
      {
        id: '1',
        name: 'A公司',
        shortName: 'A',
        code: '001',
        contactPerson: '小A',
        contactPhone: '15556666999',
        createTime: '2024-11-02 12:00:00',
        operator: '小李'
      },
      {
        id: '2',
        name: 'B公司',
        shortName: 'B',
        code: '002',
        contactPerson: '小B',
        contactPhone: '16999998888',
        createTime: '2024-11-01 22:00:00',
        operator: '小李'
      }
    ]
    
    // 设置总条数
    pagination.total = tableData.value.length
  } catch (error) {
    console.error('获取数据失败', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchTableData()
}

// 页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchTableData()
}

// 添加公司
const handleAdd = () => {
  // 重置表单
  Object.keys(companyForm).forEach(key => {
    companyForm[key] = ''
  })
  
  dialogTitle.value = '新增公司'
  dialogVisible.value = true
}

// 编辑公司
const handleEdit = (row) => {
  // 填充表单
  Object.keys(companyForm).forEach(key => {
    if (key in row) {
      companyForm[key] = row[key]
    }
  })
  
  dialogTitle.value = '编辑公司'
  dialogVisible.value = true
}

// 删除公司
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm('确定要删除选中的公司吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行删除操作
    ElMessage.success('删除成功')
    fetchTableData()
  }).catch(() => {
    // 取消删除
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 查看日志
const handleLog = () => {
  // 模拟日志数据
  logData.value = [
    {
      id: '1',
      operateType: '新增',
      content: '新增公司: A公司',
      operateTime: '2024-11-02 12:00:00',
      operator: '小李'
    },
    {
      id: '2',
      operateType: '修改',
      content: '修改公司: B公司',
      operateTime: '2024-11-01 22:00:00',
      operator: '小李'
    }
  ]
  
  logPagination.total = logData.value.length
  logDialogVisible.value = true
}

// 日志分页大小变化
const handleLogSizeChange = (size) => {
  logPagination.pageSize = size
  // 获取日志数据
}

// 日志页码变化
const handleLogCurrentChange = (page) => {
  logPagination.currentPage = page
  // 获取日志数据
}

// 提交表单
const submitForm = async () => {
  if (!companyFormRef.value) return
  
  await companyFormRef.value.validate((valid, fields) => {
    if (valid) {
      // 这里添加提交逻辑
      console.log('提交表单', companyForm)
      ElMessage.success(companyForm.id ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchTableData()
    } else {
      console.log('表单校验失败', fields)
      return false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
.company-setting-container {
  .form-row {
    display: flex;
    margin-bottom: 20px;
    
    .el-form-item {
      flex: 1;
      margin-right: 20px;
      
      &:last-child {
        margin-right: 0;
      }
    }
    
    &.full-width {
      display: block;
      
      .full-width-item {
        width: 100%;
      }
    }
  }
}
</style> 